/**
 * @description Register Component
 */

import React, { Component, Fragment } from 'react'
import PropTypes from 'prop-types'
import {
  Form,
  Input,
  Tooltip,
  Icon,
  Cascader,
  Select,
  Row,
  Col,
  Checkbox,
  Button,
  AutoComplete,
  notification,
  Affix
} from 'antd'
import classNames from 'classnames'
import Api from '@api'
import Animate from 'rc-animate'
import { Link } from 'react-router-dom'
import { FormattedMessage, injectIntl, intlShape } from 'react-intl'

const FormItem = Form.Item
const Option = Select.Option
const AutoCompleteOption = AutoComplete.Option
// Address options
const residences = [
  {
    value: 'zhejiang',
    label: 'Zhejiang',
    children: [
      {
        value: 'hangzhou',
        label: 'Hangzhou',
        children: [
          {
            value: 'xihu',
            label: 'West Lake'
          }
        ]
      }
    ]
  },
  {
    value: 'jiangsu',
    label: 'Jiangsu',
    children: [
      {
        value: 'nanjing',
        label: 'Nanjing',
        children: [
          {
            value: 'zhonghuamen',
            label: 'Zhong Hua Men'
          }
        ]
      }
    ]
  }
]

class RegistrationForm extends Component {
  static propTypes = {
    form: PropTypes.object,
    history: PropTypes.object,
    intl: intlShape.isRequired
  }
  state = {
    confirmDirty: false,
    autoCompleteResult: []
  }
  handleSubmit = e => {
    e.preventDefault()
    this.props.form.validateFieldsAndScroll((err, values) => {
      // TODO: Handle submit
      if (!err) {
        Api.post('register', values, true).then(res => {
          notification.success({
            message: this.props.intl.formatMessage({
              id: 'i18n_common_success'
            }),
            description: JSON.stringify(res)
          })
          this.props.history.push('/login')
        })
      }
    })
  }
  handleConfirmBlur = e => {
    const value = e.target.value
    this.setState({ confirmDirty: this.state.confirmDirty || !!value })
  }
  compareToFirstPassword = (rule, value, callback) => {
    const form = this.props.form
    if (value && value !== form.getFieldValue('password')) {
      callback(
        this.props.intl.formatMessage({
          id: 'i18n_register_password_inconsistent_label'
        })
      )
    } else {
      callback()
    }
  }
  validateToNextPassword = (rule, value, callback) => {
    const form = this.props.form
    if (value && this.state.confirmDirty) {
      form.validateFields(['confirm'], { force: true })
    }
    callback()
  }
  handleWebsiteChange = value => {
    let autoCompleteResult
    if (!value) {
      autoCompleteResult = []
    } else {
      autoCompleteResult = ['.com', '.org', '.net'].map(
        domain => `${value}${domain}`
      )
    }
    this.setState({ autoCompleteResult })
  }
  // Set language to localStorage
  setLanguage() {
    const curLan = localStorage.getItem('ri-lan')
    localStorage.setItem('ri-lan', curLan === 'en' ? 'zh' : 'en')
    // FIXME: will do smooth reload
    window.location.reload()
  }
  render() {
    const { getFieldDecorator } = this.props.form
    const { autoCompleteResult } = this.state

    const formItemLayout = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 10 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 14 }
      }
    }
    const tailFormItemLayout = {
      wrapperCol: {
        xs: {
          span: 24,
          offset: 0
        },
        sm: {
          span: 14,
          offset: 10
        }
      }
    }
    const prefixSelector = getFieldDecorator('prefix', {
      initialValue: '86'
    })(
      <Select style={{ width: 70 }}>
        <Option value="86">+86</Option>
        <Option value="87">+87</Option>
      </Select>
    )

    const websiteOptions = autoCompleteResult.map(website => (
      <AutoCompleteOption key={website}>{website}</AutoCompleteOption>
    ))

    const { formatMessage } = this.props.intl
    const registerClass = classNames(
      'd-flex justify-content-center bg-layout align-items-center h-100'
    )
    return (
      <Fragment>
        <Affix className="position-absolute adjust-language-position ">
          <Button icon="global" onClick={this.setLanguage}>
            <FormattedMessage id="i18n_login_switch_language_label" />
          </Button>
        </Affix>
        <Animate
          transitionName="fade"
          transitionAppear={true}
          className={registerClass}
        >
          <Form onSubmit={this.handleSubmit} className="mt-3">
            <FormItem
              {...formItemLayout}
              label={
                <span>
                  {formatMessage({ id: 'i18n_register_nickname_label' })}
                  <Tooltip
                    title={formatMessage({
                      id: 'i18n_register_nickname_tooltip_label'
                    })}
                  >
                    <Icon type="question-circle-o" className="ml-1" />
                  </Tooltip>
                </span>
              }
            >
              {getFieldDecorator('nickname', {
                rules: [
                  {
                    required: true,
                    message: formatMessage({
                      id: 'i18n_register_nickname_valid_label'
                    }),
                    whitespace: true
                  }
                ]
              })(<Input />)}
            </FormItem>
            <FormItem
              {...formItemLayout}
              label={formatMessage({ id: 'i18n_login_user_password_label' })}
            >
              {getFieldDecorator('password', {
                rules: [
                  {
                    required: true,
                    message: formatMessage({
                      id: 'i18n_login_user_password_valid_label'
                    })
                  },
                  {
                    validator: this.validateToNextPassword
                  }
                ]
              })(<Input type="password" />)}
            </FormItem>
            <FormItem
              {...formItemLayout}
              label={formatMessage({
                id: 'i18n_register_password_confirm_label'
              })}
            >
              {getFieldDecorator('confirm', {
                rules: [
                  {
                    required: true,
                    message: formatMessage({
                      id: 'i18n_register_password_confirm_valid_label'
                    })
                  },
                  {
                    validator: this.compareToFirstPassword
                  }
                ]
              })(<Input type="password" onBlur={this.handleConfirmBlur} />)}
            </FormItem>
            <FormItem
              {...formItemLayout}
              label={formatMessage({ id: 'i18n_register_email_label' })}
            >
              {getFieldDecorator('email', {
                rules: [
                  {
                    type: 'email',
                    message: formatMessage({
                      id: 'i18n_register_email_valid_fail_label'
                    })
                  },
                  {
                    required: true,
                    message: formatMessage({
                      id: 'i18n_register_email_valid_require_label'
                    })
                  }
                ]
              })(<Input />)}
            </FormItem>
            <FormItem
              {...formItemLayout}
              label={formatMessage({ id: 'i18n_register_phone_label' })}
            >
              {getFieldDecorator('phone', {
                rules: [
                  {
                    required: true,
                    message: formatMessage({
                      id: 'i18n_register_phone_valid_label'
                    })
                  }
                ]
              })(<Input addonBefore={prefixSelector} class="w-100" />)}
            </FormItem>
            <FormItem
              {...formItemLayout}
              label={formatMessage({ id: 'i18n_register_residence_label' })}
            >
              {getFieldDecorator('residence', {
                initialValue: ['zhejiang', 'hangzhou', 'xihu'],
                rules: [
                  {
                    type: 'array',
                    required: true,
                    message: formatMessage({
                      id: 'i18n_register_residence_valid_label'
                    })
                  }
                ]
              })(<Cascader options={residences} />)}
            </FormItem>
            <FormItem
              {...formItemLayout}
              label={formatMessage({ id: 'i18n_register_website_label' })}
            >
              {getFieldDecorator('website', {
                rules: [
                  {
                    required: true,
                    message: formatMessage({
                      id: 'i18n_register_website_valid_label'
                    })
                  }
                ]
              })(
                <AutoComplete
                  dataSource={websiteOptions}
                  onChange={this.handleWebsiteChange}
                >
                  <Input />
                </AutoComplete>
              )}
            </FormItem>
            <FormItem
              {...formItemLayout}
              label={
                <span>
                  {formatMessage({ id: 'i18n_register_captcha_label' })}
                  <Tooltip
                    title={
                      <span>
                        {formatMessage({
                          id: 'i18n_register_captcha_tooltip_label'
                        })}
                        <Icon type="smile-o" className="ml-1" />
                      </span>
                    }
                  >
                    <Icon type="question-circle-o" className="ml-1" />
                  </Tooltip>
                </span>
              }
            >
              <Row gutter={8}>
                <Col span={12}>
                  {getFieldDecorator('captcha', {
                    rules: [
                      {
                        required: true,
                        message: formatMessage({
                          id: 'i18n_register_captcha_valid_label'
                        })
                      }
                    ]
                  })(<Input />)}
                </Col>
                <Col span={12}>
                  <Button>
                    {formatMessage({ id: 'i18n_register_captcha_btn_label' })}
                  </Button>
                </Col>
              </Row>
            </FormItem>
            <FormItem {...tailFormItemLayout}>
              {getFieldDecorator('agreement', {
                valuePropName: 'checked'
              })(
                <Checkbox>
                  {formatMessage({ id: 'i18n_register_agreement_read_label' })}
                  <a href="" className="ml-1">
                    {formatMessage({ id: 'i18n_register_agreement_label' })}
                  </a>
                </Checkbox>
              )}
            </FormItem>
            <FormItem {...tailFormItemLayout}>
              <Button type="primary" htmlType="submit" className="w-100">
                <FormattedMessage id="i18n_register_label" />
              </Button>
              <Link to="/login">
                <Icon type="rollback" className="mr-1" />
                <FormattedMessage id="i18n_register_back_login_label" />
              </Link>
            </FormItem>
          </Form>
        </Animate>
      </Fragment>
    )
  }
}

const Register = Form.create()(RegistrationForm)

export default injectIntl(Register)
